/*{
 code:1,
 mess:"", //系统报错的信息 code =0

 }
 {
 code:1,
 mess:"", //系统报错的信息 code =0
 data:{
 业务
 }
 }
 */
(function (global, $, undefined) {
    function rest(type, url, data, callback) {
        if (typeof data === "function") {
            callback = data;
            data = {};
        }

        var der = $.Deferred();
        $.ajax({
            type: type,
            url: url,
            data: data,
            dataType: "json",
            // contentType: "application/json;charset=UTF-8",
            success: function (rs) {
                if (rs.mess == undefined) rs.mess = null;
                if (rs.code === -1) {
                    window.location.href = "/user/oauthLogin"
                } else if (rs.code === 1) {
                    if (typeof callback === 'function') {
                        callback.call(this, rs.mess, rs.data);
                    }
                    der.resolveWith(this, [rs.mess, rs.data]);
                } else {
                    der.rejectWith(this, [rs.mess]);
                }
            },
            error: function () {
                der.rejectWith(this);
            }
        });

        return der.promise();
    }

    $.extend({
        restGet: function () {
            return rest.apply(this, ['GET'].concat(Array.prototype.slice.call(arguments, 0)));
        },
        restPost: function () {
            return rest.apply(this, ['POST'].concat(Array.prototype.slice.call(arguments, 0)));
        },
    });


    //全局 弹出层提示报错 依赖layer 弹出层
    function BaseMessDialog(mess, time) {
        layer.open({
            content: mess
            , skin: 'msg'
            , time: time //2秒后自动关闭
        });
    }

    $.extend({
        getUserInfo: function (callback) {
            $.restPost('/user/doGetLocalUser').done(function (mess, data) {
                callback(mess, data);
            }).fail(function (mess) {
                $.rootErrorDialog(mess, 2000);
            });
        }
    });

    $.extend({

        rootErrorDialog: function (mess, time) {
            var rootError = mess || "网络延迟,请刷新";
            return BaseMessDialog(rootError, time)
        },
        rootSuccessDialog: function (mess, time) {
            var rootSuccess = mess || "成功了";

            return BaseMessDialog(rootSuccess, time)
        },
        rootOpenDialog: function (opt) {

            var opt = $.extend({
                title: false,
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 1, //不显示关闭按钮
                shift: '4',
                shadeClose: false, //开启遮罩关闭
                content: '...',
                area: '60%'
            }, opt);
            return layer.open(opt);
        },

        //右下角弹出的信息框
        rootOpenMsgDialog: function (opt) {
            var opt = $.extend({
                skin: 'layui-layer-molv',
                title: '开奖通告',
                content: '我是弹出的中奖信息框',
                offset: 'rb',
                shift: 2,
                shade: 0,
                time: 30000
            }, opt);
            return layer.open(opt);
        }
    });

    //创建补0函数
    function p(s) {
        return s < 10 ? '0' + s : s;
    }

    /**
     * 兼容ios 安卓时间
     * @param value
     * @returns {XML|void|*|string|{by}}
     * @constructor
     */
    function GetDateFormat(value) {
        var pointIndex = value.indexOf(".");
        if (pointIndex >= 0) {
            value = value.substring(0, pointIndex);
        }
        return value.replace(/\-/g, "/");
        // return value.replace(' ', 'T');
    }

    $.extend({
        loadJs: function (url, callback) {
            var done = false;
            var script = document.createElement('script');
            script.type = 'text/javascript';//do not 'application/javascript',because Low version of the browser is not compatible
            script.language = 'javascript';
            script.charset = "utf-8";
            script.src = url;
            //script.setAttribute('src', url);
            script.onload = script.onreadystatechange = function () {
                if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')) {
                    done = true;
                    script.onload = script.onreadystatechange = null;
                    if (callback) {
                        console.log('load ' + url + ' success.');
                        callback.call(script);
                    }
                }
            };
            document.getElementsByTagName("head")[0].appendChild(script);
        }
    });

    //返回 01-12 的月份值
    function getMonth(date) {
        var month = "";
        month = date.getMonth() + 1; //getMonth()得到的月份是0-11
        if (month < 10) {
            month = "0" + month;
        }
        return month;
    }

    //返回01-30的日期
    function getDay(date) {
        var day = "";
        day = date.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        return day;
    }

    $.extend({
        dateFormatUtil: function (longTypeDate) {
            var dateTypeDate = "";
            var date = new Date();
            date.setTime(longTypeDate);
            dateTypeDate += date.getFullYear();   //年
            dateTypeDate += "-" + getMonth(date); //月
            dateTypeDate += "-" + getDay(date);   //日
            return dateTypeDate;
        },
        getDays: function (strDateStart, strDateEnd) {
            var strSeparator = "/"; //日期分隔符
            var oDate1;
            var oDate2;
            var iDays;
            oDate1 = strDateStart.split(strSeparator);
            oDate2 = strDateEnd.split(strSeparator);
            var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
            var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
            iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24)//把相差的毫秒数转换为天数
            return iDays;
        },
        AddDays: function (num) {
            var newdate = new Date();
            var newtimems = newdate.getTime() - (num * 24 * 60 * 60 * 1000);
            newdate.setTime(newtimems);
            var time = newdate.getFullYear() + "-" + (newdate.getMonth() + 1) + "-" + newdate.getDate();
            return time;
        },
        getTime: function () {
            var d = new Date();
            var YMDHMS = d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
            return YMDHMS
        },
        getYMD: function (date) {
            if (date == undefined)
                date = new Date();
            else
                date = new Date(date);
            var YMD = date.getFullYear() + "/" + p(date.getMonth() + 1) + "/" + p(date.getDate());
            return YMD
        },
        getTargetDate: function (date) {
            var d = new Date(GetDateFormat(date));
            var ymd = d.getFullYear() + "/" + p(d.getMonth() + 1) + "/" + p(d.getDate());
            return ymd;
        },
        getTargetFullDate: function (date) {
            var d = new Date(GetDateFormat(date));
            var YMDHMS = d.getFullYear() + "/" + p(d.getMonth() + 1) + "/" + p(d.getDate()) + " " + p(d.getHours()) + ":" + p(d.getMinutes()) + ":" + p(d.getSeconds());
            return YMDHMS;
        },

        hiddenPhoneCode: function (phoneCode) {
            return phoneCode.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
        },

        printUrl: 'http://114.55.107.209:8082/',
        getUrlLocation: function () {
            var hrefhash = window.location.hash;
            var hrefhashArr = hrefhash.split("/");

            return hrefhashArr[hrefhashArr.length - 1];
        },
        textre: function (t) {
            t.value = t.value.replace(/[^\-\d\.]/g, "").replace(/(^|\D)\.+/g, "$1").replace(/^(\-?\d*\.?\d*).*$/, "$1").replace(/^(\-?(\d\.?){1,4}).*$/, "$1");
        },
        isNotANumber: function (inputData) {
            //isNaN(inputData)不能判断空串或一个空格
            //如果是一个空串或是一个空格，而isNaN是做为数字0进行处理的，而parseInt与parseFloat是返回一个错误消息，这个isNaN检查不严密而导致的。
            if (parseFloat(inputData).toString() == "NaN") {
                //alert("请输入数字……");注掉，放到调用时，由调用者弹出提示。
                return false;
            } else {
                return true;
            }
        },
        toDecimal: function (x) {
            var f = parseFloat(x);
            if (isNaN(f)) {
                return;
            }
            f = Math.round(x * 10000) / 10000;
            return f;
        },

        hidebankCard: function (str) {
            var reg = /^(\d{4})\d+(\d{4})$/;
            return str.replace(reg, "$1****$2");
        },

        //截取地址欄參數
        GetQueryString: function (name) {
            var location = decodeURIComponent(window.location.search);
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = location.substr(1).match(reg);
            if (r != null)return unescape(r[2]);
            return null;
        },

        //删除参数值
        delQueStr: function (url, ref) {
            var str = "";
            if (url.indexOf('?') != -1) {
                str = url.substr(url.indexOf('?') + 1);
            }
            else {
                return url;
            }
            var arr = "";
            var returnurl = "";
            var setparam = "";
            if (str.indexOf('&') != -1) {
                arr = str.split('&');
                for (i in arr) {
                    if (arr[i].split('=')[0] != ref) {
                        returnurl = returnurl + arr[i].split('=')[0] + "=" + arr[i].split('=')[1] + "&";
                    }
                }
                return url.substr(0, url.indexOf('?')) + "?" + returnurl.substr(0, returnurl.length - 1);
            }
            else {
                arr = str.split('=');
                if (arr[0] == ref) {
                    return url.substr(0, url.indexOf('?'));
                }
                else {
                    return url;
                }
            }
        },

        //手机号码格式验证
        IsTel: function (Tel) {
            var re = new RegExp(/^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/);
            var retu = Tel.match(re);
            if (retu) {
                return true;
            } else {
                return false;
            }
        },

        //判斷對象是否為空
        isEmptyObject: function (obj) {
            for (var name in obj) {
                return false;//返回false，不为空对象
            }
            return true;//返回true，为空对象
        },
        isCardNo: function (card) {
            // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if (reg.test(card) === false) {
                return "身份证输入不合法";
            }
            return "";
        },

        /** 数字金额大写转换(可以处理整数,小数,负数) */
        smalltoBIG: function (n) {
            var fraction = ['角', '分'];
            var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
            var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
            var head = n < 0 ? '欠' : '';
            n = Math.abs(n);

            var s = '';

            for (var i = 0; i < fraction.length; i++) {
                s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
            }
            s = s || '整';
            n = Math.floor(n);

            for (var i = 0; i < unit[0].length && n > 0; i++) {
                var p = '';
                for (var j = 0; j < unit[1].length && n > 0; j++) {
                    p = digit[n % 10] + unit[1][j] + p;
                    n = Math.floor(n / 10);
                }
                s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
            }
            return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
        },

        urlencode: function (str) {
            str = (str + '').toString();
            return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
        },

        initBootstrapTable: function (id, option) {
            var $table = $("#" + id);
            //先销毁表格
            $table.bootstrapTable("destroy");

            var defaultOption = {
                undefinedText: '-',
                striped: true, //表格显示条纹
                pagination: true, //启动分页
                pageSize: 10, //每页显示的记录数
                pageNumber: 1, //当前第几页
                searchAlign: "right", //设置搜索框位置
                showPaginationSwitch: false,
                search: true, //是否启用查询
                searchOnEnterKey: false, //回车搜索
                sortOrder: "desc",
                showRefresh: true, //显示刷新按钮
                clickToSelect: false, //设置true 将在点击行时，自动选择rediobox 和 checkbox
                paginationPreText: "上一页", //指定分页条中上一页按钮的图标或文字
                paginationNextText: "下一页", ////指定分页条中下一页按钮的图标或文字
                //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                //设置为limit可以获取limit, offset, search, sort, order
                queryParamsType: "undefined",
                showExport: false,
                exportDataType: 'all',
                onLoadSuccess: function () { //加载成功时执行
                },
                onLoadError: function () { //加载失败时执行
                },
                onSearch: function () {

                }
                // onPageChange:function(){

                // }
            };
            //是否导出
            if (option.hasOwnProperty('isExport') && option.isExport) {
                defaultOption.showExport = true; //是否显示导出
                defaultOption.exportDataType = "all"; //basic', 'all', 'selected'.
            }
            var defaultColumn = {
                field: "", //取的字段值（必需）
                title: "", //展示列名（必需）
                sortable: true, //是否排序
                formatter: undefined //用于字段处理,function
            };
            var columns = option.columns;
            $(columns).each(function (i, column) {
                columns[i] = $.extend({}, defaultColumn, column);
            });
            option = $.extend({}, defaultOption, option);
            $table.bootstrapTable(option);

            //footer的宽度
            $('.fixed-table-footer table tbody tr td').each(function (i, item) {
                $(item).css('width', option.columns[i].width == undefined ? '' : option.columns[i].width);
            });
        }
    });
})(window, jQuery);